const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    activeNav: 'all',
    navs: [{
      text: '全部',
      alias: 'all'
    }, {
      text: '待付款',
      alias: 'unpaid'
    }, {
      text: '待发货',
      alias: 'undelivered'
    }, {
      text: '待收货',
      alias: 'unreceived'
    }],
    orderList: [], //展示列表
    allList: [], //全部订单
    unpaidList: [], //待付款列表
    undeliveredList: [], //待发货列表
    unreceivedList: [], //待收货列表
  },

  onLoad(options) {
    console.log("onLoad")
    const that = this;
    console.log(options)
    //获取用户id
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userId: userInfo.openId
    })
    //获取所有订单
    that.getAllorders(options.t);
    // that.changeList(options.t);
    if (options.t) {
      this.setData({
        activeNav: options.t
      });
    }
  },

  /* 获得所有订单 */
  getAllorders(option) {
    var url = wx.getStorageSync("config")
    let that = this;
    let userId = that.data.userId;
    wx.request({
      url: url.service.homeUrl + "/huiguniang/order/selectAll?openId=" + userId + "&pageStart=1&pageSize=99",
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        // console.log("success orderList")
        console.log(res)
        if (res.data.status.returnCode === 1) {
          that.setData({
            orderList: res.data.result,
            allList: res.data.result,
            imgUrl: url.service.imgUrl
          })
          that.filterData(option);
        }
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  /* 筛选数据 */
  filterData(res) {
    let that = this;
    let orderList = that.data.allList;
    //待付款列表
    let payList = [];
    //待发货列表
    let shipList = [];
    //待收货列表
    let receiptList = [];
    for (let i = 0; i < orderList.length; i++) {
      let list = orderList[i];
      let temOption = {};
      //待付款列表
      if (list.isPay === 0) {
        temOption = list;
        temOption.test1 = '取消订单';
        temOption.test2 = '去支付';
        temOption.test3 = '等待付款';
        payList.push(temOption);
        //待发货列表
      } else if (list.isDelivered === 0 && list.isPay === 1) {
        temOption = list;
        temOption.test1 = '提醒发货';
        temOption.test2 = '查看物流';
        temOption.test3 = '买家已付款';
        shipList.push(temOption);
        //待收货列表
      } else if (list.isReceipt === 0 && list.isDelivered === 1 && list.isPay === 1) {
        temOption = list;
        temOption.test1 = '查看物流';
        temOption.test2 = '确认收货';
        temOption.test3 = '卖家已发货';
        receiptList.push(temOption);
      }
    }
    that.setData({
      payList: payList,
      shipList: shipList,
      receiptList: receiptList
    })
    if (res) {
      that.render(res);
    }
  },




  /* 初始化 */
  render(res) {
    console.log(res)
    let that = this;
    let alias = res;
    let allList = that.data.allList; //全部列表
    let unpaidList = that.data.payList; //待付款列表
    let undeliveredList = that.data.shipList; //待发货列表
    let unreceivedList = that.data.receiptList; //待收货列表
    if (alias === "unpaid") {
      that.setData({
        orderList: unpaidList,
      })
    } else if (alias === "undelivered") {
      that.setData({
        orderList: undeliveredList,
      })
    } else if (alias === "unreceived") {
      that.setData({
        orderList: unreceivedList,
      })
    } else {
      that.setData({
        orderList: allList
      })
    }
  },


  /* 导航页切换 */
  changeList(e) {
    const that = this;
    let alias = e.target.dataset.alias;
    console.log(alias)
    let allList = that.data.allList; //全部列表
    let unpaidList = that.data.payList; //待付款列表
    let undeliveredList = that.data.shipList; //待发货列表
    let unreceivedList = that.data.receiptList; //待收货列表
    if (alias === "unpaid") {
      that.setData({
        orderList: unpaidList,
      })
    } else if (alias === "undelivered") {
      that.setData({
        orderList: undeliveredList,
      })
    } else if (alias === "unreceived") {
      that.setData({
        orderList: unreceivedList,
      })
    } else {
      that.setData({
        orderList: allList
      })
    }

    if (alias !== this.data.activeNav) {
      this.setData({
        activeNav: e.target.dataset.alias,
        loading: true
      });
    }
  },



  btn1(e) {
    let item = e.target.dataset.option;
    var url = wx.getStorageSync("config");
    let that = this;
    let userId = that.data.userId;
    let orderNumber = item.orderNumber;
    let activeNav = that.data.activeNav; //当前选中tab
    if (item.test1 === '取消订单') {
      wx.showModal({
        title: '取消订单',
        content: '是否取消订单？',
        success: function(res) {
          if (res.cancel) {
            //点击取消,默认隐藏弹框
          } else {

            wx.request({
              url: url.service.homeUrl + "/huiguniang/order/updateOrder?orderNumber=" + orderNumber + "&isPay=" + 2,
              method: 'PUT',
              header: {
                'Content-Type': 'application/json'
              },
              success: function(res) {
                if (res.data.status.code === 1) {
                  wx.showToast({
                    title: '取消成功',
                    icon: 'success'
                  })
                }
                let link = {
                  t: activeNav
                }
                that.onLoad(link);
              },
              fail: function(res) {},
              complete: function(res) {},
            })
          }
        }
      })
    }
  },

  btn2(e) {
    let item = e.target.dataset.option;
    var url = wx.getStorageSync("config");
    let prepayId = wx.getStorageSync('prepayId');
    let that = this;
    let userId = that.data.userId;
    let orderNumber = item.orderNumber;
    if (item.test2 === '确认收货') {
      wx.showModal({
        title: '确认收货',
        content: '是否确认收货？',
        success: function(res) {
          if (res.cancel) {
            //点击取消,默认隐藏弹框
          } else {
            wx.request({
              url: url.service.homeUrl + "/huiguniang/order/updateOrder?orderNumber=" + orderNumber + "&isReceipt=" + 1,
              method: 'PUT',
              header: {
                'Content-Type': 'application/json'
              },
              success: function(res) {
                if (res.data.status.code === 1) {
                  wx.showToast({
                    title: '收货成功',
                    icon: 'success'
                  })
                }
                let link = {
                  t: "unreceived"
                }
                that.onLoad(link);
              },
              fail: function(res) {},
              complete: function(res) {},
            })
          }
        }
      })
    } else if (item.test2 === '去支付') {

      var timestamp = Date.parse(new Date()); //获取时间戳
      timestamp = timestamp / 1000;
      var v2 = timestamp.toString();
      let appid = 'wx56ba2719d169bce3';
      let key = '85AAADAECACF8195E614EE5D82582371';

      //生成sign
      function paySign(appid, nonceStr, prepay_id, timestamp, key) {
        var sign = ''
        //签名顺序按照ASCII字典序排序
        var signA = "appId=" + appid + "&nonceStr=" + nonceStr + "&package=prepay_id=" + prepayId + "&signType=MD5&timeStamp=" + timestamp
        var signB = signA + "&key=" + key
        // console.log(signB)
        sign = md5.md5(signB).toUpperCase()
        return sign
      }

      //生成nonceStr
      function getNonceStr(len) {
        len = len || 32
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
        var maxPos = $chars.length
        var str = ''
        for (var i = 0; i < len; i++) {
          str += $chars.charAt(Math.floor(Math.random() * maxPos))
        }
        return str
      }

      let nonceStr = getNonceStr();

      wx.requestPayment({
        appId: 'wx56ba2719d169bce3',
        timeStamp: v2,
        nonceStr: nonceStr,
        package: 'prepay_id=' + prepayId,
        signType: 'MD5',
        paySign: paySign(appid, nonceStr, prepayId, v2, key),
        success: function(res) {
          wx.showModal({
            title: '支付成功！',
            showCancel: false, //是否显示取消按钮
            success: function(res) {
              if (res.cancel) {
                //点击取消,默认隐藏弹框
              } else {
                //点击确定
                let link = {
                  t: "undelivered"
                }
                that.onLoad(link);
              }
            },
          })
        },
        fail: function(res) {
          wx.showModal({
            title: '支付失败！',
            showCancel: false, //是否显示取消按钮
            success: function(res) {
              if (res.cancel) {
                //点击取消,默认隐藏弹框
              } else {
                //点击确定
                let link = {
                  t: "undelivered"
                }
                that.onLoad(link);
              }
            },
          })
        }
      })
    }
  },

  /* 删除订单 */
  del(e) {
    var url = wx.getStorageSync("config");
    let orderNumber = e.target.dataset.ordernumber;
    console.log(e.target.dataset)
    let that = this;
    let userId = that.data.userId;
    let activeNav = that.data.activeNav;
    wx.showModal({
      title: '删除订单',
      content: '确定要删除吗？',
      success: function(res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          wx.request({
            url: url.service.homeUrl + "/huiguniang/order/deleteByOrderNumber?userId=" + userId + "&orderNumber=" + orderNumber,
            method: 'DELETE',
            header: {
              'Content-Type': 'application/json'
            },
            success: function(res) {
              if (res.data.status.code === 1) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
              }
              let link = {
                t: activeNav
              }
              that.onLoad(link);
            },
            fail: function(res) {},
            complete: function(res) {},
          })
        }
      }
    })
  },
})